<?php

namespace App\Models;

use Cache;

class BucketCategory extends BaseModel
{
    protected $table = "bucket_category";

    const BUCKET_DATA = 'BUCKET_DATA';
    const BUCKET_ALL_DATA = 'BUCKET_ALL_DATA';

    protected $rules = [
        'title' => 'required|between:1,8|unique:bucket_category,title',
    ];

    protected $message = [
        'title.required' => '水桶品牌名称必须填写',
        'title.between' => '水桶品牌名称不合法必须1-8个字',
        'title.unique' => '该水桶品牌名称已存在，请勿重复添加',
    ];

    /**
     * 获取品牌详细信息
     * @param  milit $id 品牌ID或标识
     * @param  boolean $field 查询字段
     * @return array     品牌信息
     */
    public function getInfo($id)
    {
        $list = $this->getALLCache();
        /* 获取品牌信息 */
        if (is_numeric($id)) { //通过ID查询
            return $list[$id];
        }
        foreach ($list as $k => $v) {
            if ($v['title'] == $id) {
                return $v;
            }
        }
        return false;
    }


    /**
     * 获取品牌树，指定品牌则返回指定品牌极其子品牌，不指定则返回所有品牌树
     * @param  integer $id 品牌ID
     * @param  string $field 查询字段
     * @return array          品牌树
     */
    public function getTree($id = 0, $field = '*')
    {
        /* 获取当前品牌信息 */
        if ($id) {
            $info = $this->getInfo($id);
            $id = $info['id'];
        }
        $list = $this->getCache();
        $list = list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_', $root = $id);

        /* 获取返回数据 */
        if (isset($info)) { //指定品牌则返回当前品牌极其子品牌
            $info['_'] = $list;
        } else { //否则返回所有品牌
            $info = $list;
        }

        return $info;
    }

    /**
     * 获取配置列表
     * @return array 配置数组
     */
    public function getCache()
    {
        $res = Cache::get(self::BUCKET_DATA);
        if (!$res) {
            $where['status'] = ['>', -1];
            $res = $this->_getList($where, '*', ['sort' => 'asc'])->toArray();
            Cache::forever(self::BUCKET_DATA, $res);
        }
        return $res;
    }

    /**
     * 获取配置列表
     * @return array 配置数组
     */
    public function getALLCache()
    {
        $category = Cache::get(self::BUCKET_ALL_DATA);
        if (!$category) {
            $category = $this->_getList();
            if ($category) {
                $res = $category->toArray();
                $category = [];
                foreach ($res as $v) {
                    $category[$v['id']] = $v;
                }
            }
            Cache::forever(self::BUCKET_ALL_DATA, $category);
        }
        return $category;
    }

    public function generate()
    {
        Cache::forget(self::BUCKET_ALL_DATA);
        Cache::forget(self::BUCKET_DATA);
    }

    public function checkParentCategory()
    {
        if (request('pid')) {
            /* 获取上级分类信息 */
            $category = $this->_getOne(['pid' => request('pid')]);
            if (!($category && 1 == $category['status'])) {
                $this->error = '指定的上级分类不存在或被禁用！';
                return false;
            }
            return $category;
        }
        return true;
    }

    public function getBrandTree()
    {
        $category = $this->_getList()->toArray();
        $category = childTree($category, 0, 'id', 'pid');
        $category = array_merge([0 => ['id' => 0, 'title' => '顶级菜单', 'prefix' => '']], $category);
        return $category;
    }

    public function operate($type)
    {
        $to = request('to');
        $from = request('from');
        $operate = $type == 'move' ? '移动' : ($type == 'merge' ? '合并' : '');
        if (!$operate) {
            $this->error = '参数错误！';
            return false;
        }
        if ($type == 'move') {
            $res = $this->_update(['id' => $from], ['pid' => $to]);
            if (!$res) {
                $this->error = '品牌移动失败！';
                return false;
            }
        }
        if ($type == 'merge') {
            $goods = new Goods();
            $goodsList = $goods->_getList(['brand_id' => $from])->toArray();
            if (!empty($goodsList)) {
                $res = $goods->_update(['brand_id' => $from], ['brand_id' => $to]);
                if (!$res) {
                    $this->error = '合并品牌失败！';
                    return false;
                }
            }
            //删除被合并的品牌
            $this->_del(['id' => $from]);
        }
        $this->generate();
        //记录行为
//        action_log('update_brand', 'brand', $from);
        return '品牌' . $operate . '成功！';
    }

    public function addOrUpdate($type = 0)
    {
        if (!$this->checkParentCategory()) {
            return false;
        }
        $data['admin_id'] = plat_admin_id();
        $data['title'] = trim(request('title'));
        if (request('id')) {
            $data['id'] = trim(request('id'));
            $this->rules['title'] .= ',' . $data['id'] . ',id' . ',admin_id,' . $data['admin_id'];
        } else {
            $this->rules['title'] .= ',' . NULL . ',' . NULL . ',admin_id,' . $data['admin_id'];
        }
        if (!$this->_validate($data) && plat_identify() == 'admin') {
            return false;
        }
        $data['status'] = 1;//前期设定添加后就默认开启，后期启用下面的注释代码，默认就是未开启
        request('sort') && $data['sort'] = request('sort');
        request('allow_publish') && $data['allow_publish'] = request('allow_publish');
        $this->_start();
        try {
            $res = $this->_save($data);
            if ($res) {
                $data['id'] = isset($data['id']) ? $data['id'] : $this->id;
                //记录行为
                $this->generate();
            }
            if ($type) {
                $shopBucketCategory = new ShopBucketCategory();
                $category = $shopBucketCategory->_getOne(['shop_id' => session('shop_info')['id']]);
                $sdata['admin_id'] = plat_admin_id();
                $sdata['shop_id'] = session('shop_info')['id'];
                $arr = ['id' => $data['id'], 'title' => $data['title']];
                if (!$category) {
                    $sdata['category_data'][0] = $arr;
                } else {
                    $sdata['id'] = $category['id'];
                    $sdata['category_data'] = $category['category_data'];
                    if (request('id')) {
                        foreach($sdata['category_data'] as &$v) {
                            if ($v['id'] == $data['id']) {
                                $v['title'] = $data['title'];
                            }
                        }
                    } else {
                        $index = count($category['category_data']);
                        $sdata['category_data'][$index] = $arr;
                    }

                }
                $shopBucketCategory->_save($sdata);
                $bucketData = new BucketData();
                $bucketDataInfo = $bucketData->_getOne(['shop_id' => session('shop_info')['id'],'bucket_category_id'=>$data['id']]);
                if (!$bucketDataInfo) {
                    $bdata['admin_id'] = plat_admin_id();
                    $bdata['shop_id'] = session('shop_info')['id'];
                    $bdata['bucket_category_id'] = $data['id'];
                    $bucketData->_save($bdata);
                }
            }
            $this->_commit();
            return true;
        } catch (\Exception $e) {
            $this->_rollBack();
            return false;
        }
    }

    public function del()
    {
        $id = request('id');
        if (!$id) {
            $this->error = '请选择要操作的数据!';
            return false;
        }
        $child = $this->_getList(['pid' => $id])->toArray();
        if (!empty($child)) {
            $this->error = '请先删除该品牌下的子品牌';
            return false;
        }
        $res = $this->_del(['id' => $id]);
        if (!$res) {
            $this->error = '删除品牌失败!';
            return false;
        }
        //记录行为
//        action_log('update_brand', 'brand', $id);
        $this->generate();
        return '删除品牌成功';
    }

}
